package io.renren.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.dao.CampaignDao;
import io.renren.entity.CampaignEntity;
import io.renren.mapper.CampaignMapper;
import io.renren.service.CampaignService;
import io.renren.util.Query;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("campaignService")
public class CampaignServiceImpl extends ServiceImpl<CampaignDao, CampaignEntity> implements CampaignService {


    @Autowired
    CampaignMapper campaignMapper;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Object category = params.get("category");
        Page<CampaignEntity> page;

        if(null != category && StringUtils.isNotEmpty(category.toString())) {

            String queryStr = category.toString().replaceAll("&amp;", "&");

            page = this.selectPage(
                    new Query<CampaignEntity>(params).getPage(),  new EntityWrapper<CampaignEntity>().eq("category", queryStr)
            );
        }else{
            page = this.selectPage(
                    new Query<CampaignEntity>(params).getPage()
            );

        }

        return new PageUtils(page);
    }

    /**
     * 查询指定用户下的所有创建的campaign
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByUID(Map<String, Object> params) {

        String ownerId = (String) params.get("userId");

        Page<CampaignEntity> page = this.selectPage(
                new Query<CampaignEntity>(params).getPage(),
                new EntityWrapper<CampaignEntity>().eq("owner_id", ownerId)
        );


        return new PageUtils(page);
    }

    @Override
    public boolean createNewCampaign(CampaignEntity campaignEntity) {

        return this.insert(campaignEntity);

    }

    @Override
    public List<CampaignEntity> queryByContentOrTagline(String content) {
        Map<String, Object> queryContent = new HashMap<>();
        queryContent.put("content", content);
        return campaignMapper.queryFullText(queryContent);
    }


}
